local SarfMailHelper = {
	setup = {
	};
};

function SarfMailHelper_GetInstance()
	return SarfMailHelper
end

function SarfMailHelper:ScanBags()
	local list = self.setup.items
	if type(list) ~= "table" then
		list = {}
		self.setup.items = list
	else
		for k,v in pairs(self.setup.items) do
			list[k].stacks = 0
			list[k].total = 0
			list[k].num = 0
			list[k].bag = -1
			list[k].slot = -1
		end
	end
	local bag, slot, itemCount, itemLink, _, itemName
	for bag = 0, 4 do
		for slot = 1, GetContainerNumSlots(bag) do
			itemLink = GetContainerItemLink(bag, slot)
			if type(itemLink) == "string" then
				itemName = GetItemInfo(itemLink)
			else
				itemName = nil
			end
			if type(itemName) == "string" and strlen(itemName) > 0 then
				_, itemCount = GetContainerItemInfo(bag, slot)
				local entry = list[itemName]
				if type(entry) ~= "table" then
					entry = {}
					entry.stacks = 0
					entry.total = 0
					entry.num = 0
					entry.bag = -1
					entry.slot = -1
					list[itemName] = entry
				end
				if ( ( entry.num == 0 or itemCount < entry.num ) ) then
					entry.bag = bag
					entry.slot = slot
					entry.num = itemCount
				end
				entry.total = entry.total + itemCount
				entry.stacks = entry.stacks + 1
			end
		end
	end
end

function SarfMailHelper:GetMail()
	local maxItems = ATTACHMENTS_MAX_RECEIVE or 16
	CheckInbox()
	self:ScanBags()
	local anyTakers = false
	for i = 1, GetInboxNumItems() do
		local packageIcon, stationeryIcon, sender, subject, money, CODAmount, daysLeft, hasItem, wasRead, wasReturned, textCreated, canReply, isGM = GetInboxHeaderInfo(i);
		if packageIcon and not isGM and hasItem then
			for item = 1, maxItems do
				local name, texture, count = GetInboxItem(i, item)
				if name then
					local entry = self.setup.items[name]
					if entry then
						if entry.num > 0 then
							TakeInboxItem(i, item)
							anyTakers = true
						end
					end
				end
			end
		end
	end
end
